package com.lapelittle.framework.service;

import com.lapelittle.framework.entity.SysUserToken;
import com.lapelittle.framework.mapper.SysUserTokenMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.UUID;

@Service
public class TokenService {
    // token有效期（24小时）
    private final static int TOKEN_EXPIRE = 24 * 60 * 60 * 1000;
    
    @Autowired
    private SysUserTokenMapper tokenMapper;
    
    public SysUserToken createToken(Long userId) {
        // 生成一个token
        String token = UUID.randomUUID().toString().replace("-", "");
        // 当前时间
        Date now = new Date();
        // 过期时间
        Date expireTime = new Date(now.getTime() + TOKEN_EXPIRE);
        
        // 判断是否生成过token
        SysUserToken tokenEntity = tokenMapper.findByUserId(userId);
        if (tokenEntity == null) {
            tokenEntity = new SysUserToken();
            tokenEntity.setUserId(userId);
            tokenEntity.setToken(token);
            tokenEntity.setExpireTime(expireTime);
            tokenMapper.insert(tokenEntity);
        } else {
            tokenEntity.setToken(token);
            tokenEntity.setExpireTime(expireTime);
            tokenMapper.update(tokenEntity);
        }
        
        return tokenEntity;
    }
    
    public SysUserToken validateToken(String token) {
        SysUserToken tokenEntity = tokenMapper.findByToken(token);
        if (tokenEntity == null || tokenEntity.getExpireTime().before(new Date())) {
            return null;
        }
        return tokenEntity;
    }
    
    public void deleteToken(Long userId) {
        tokenMapper.deleteByUserId(userId);
    }
    
    /**
     * 清理过期的token
     * @return 清理的数量
     */
    public int cleanExpiredTokens() {
        return tokenMapper.deleteExpiredTokens();
    }
} 